﻿using Entity;
using IRepository;
using IService;
using System;
using System.Collections.Generic;

namespace Service
{
    public class NumberingRuleService : IService.INumberingRuleService
    {
        private readonly INumberingRuleRepository _repository;

        public NumberingRuleService(INumberingRuleRepository repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// 根据ID获取编号规则
        /// </summary>
        public NumberingRule GetById(int ruleId)
        {
            if (ruleId <= 0)
                throw new ArgumentOutOfRangeException(nameof(ruleId), "规则ID必须大于0");

            return _repository.GetById(ruleId);
        }

        /// <summary>
        /// 保存编号规则（新增/更新）
        /// </summary>
        public int SaveRule(NumberingRule rule)
        {
            if (rule == null)
                throw new ArgumentNullException(nameof(rule));

            // 服务层额外验证
            if (rule.RuleID == 0)
            {
                // 新增时检查是否已存在相同的目标表单和前缀
                var existingRules = QueryByConditions(new NumberingRuleQueryParams
                {
                    TargetID  = rule.TargetID,
                    NumberPrefix = rule.NumberPrefix
                });

                if (existingRules.Count > 0)
                {
                    throw new InvalidOperationException($"已存在相同的目标表单「{rule.TargetID}」和编号前缀「{rule.NumberPrefix}」的规则");
                }
            }

            return _repository.SaveRule(rule);
        }

        /// <summary>
        /// 多条件查询编号规则
        /// </summary>
        public List<NumberingRule> QueryByConditions(NumberingRuleQueryParams queryParams)
        {
            if (queryParams == null)
                queryParams = new NumberingRuleQueryParams();

            return _repository.GetByConditions(queryParams);
        }

        /// <summary>
        /// 获取最大流水号
        /// </summary>
        public int GetMaxSerialNumber(string targetForm, string numberPrefix)
        {
            if (string.IsNullOrWhiteSpace(targetForm))
                throw new ArgumentException("目标表单不能为空");

            if (string.IsNullOrWhiteSpace(numberPrefix))
                throw new ArgumentException("编号前缀不能为空");

            return _repository.GetMaxSerialNumber(targetForm, numberPrefix);
        }

        /// <summary>
        /// 更新流水号
        /// </summary>
        public int UpdateSerialNumber(string targetForm, string numberPrefix, int newSerialNumber)
        {
            if (string.IsNullOrWhiteSpace(targetForm))
                throw new ArgumentException("目标表单不能为空");

            if (string.IsNullOrWhiteSpace(numberPrefix))
                throw new ArgumentException("编号前缀不能为空");

            if (newSerialNumber < 0)
                throw new ArgumentOutOfRangeException("流水号不能为负数");

            return _repository.UpdateSerialNumber(targetForm, numberPrefix, newSerialNumber);
        }
    }
}
